"use client"

import { useState, useRef, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Loader2, Play, Upload } from "lucide-react"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Separator } from "@/components/ui/separator"
import dynamic from "next/dynamic"
import GraphComponent from "./GraphComponent"

// 定义类型
interface GraphNode {
  id: string
  label: string
  color: string
  size: number
  timestamp: number
}

interface GraphLink {
  id: string
  source: string
  target: string
  weight: number
  timestamp: number
}

interface GraphData {
  nodes: GraphNode[]
  links: GraphLink[]
}

interface VisualizationData {
  cosmographData: {
    nodes: GraphNode[]
    links: GraphLink[]
  }
}

interface GraphVisualizationProps {
  data: VisualizationData
}

// 动态导入Cosmograph组件以避免SSR问题
const DynamicCosmograph = dynamic(
  () => import("@cosmograph/react").then((mod) => mod.Cosmograph),
  { ssr: false, loading: () => <LoadingState /> }
)

const LoadingState = () => (
  <div className="flex flex-col items-center justify-center py-8">
    <Loader2 className="h-8 w-8 animate-spin text-primary mb-4" />
    <p>加载中...</p>
  </div>
)

// 图谱可视化组件
function GraphVisualization({ data }: GraphVisualizationProps) {
  const [mounted, setMounted] = useState(false)

  useEffect(() => {
    setMounted(true)
  }, [])

  if (!mounted) {
    return null
  }

  return (
    <div className="h-[800px] w-full border rounded-lg overflow-hidden bg-black">
      <DynamicCosmograph
        nodes={data.cosmographData.nodes}
        links={data.cosmographData.links}
        nodeColor={(node: any) => node.color}
        nodeSize={(node: any) => node.size}
        backgroundColor="#000000"
        linkColor="#999"
        linkWidth={1}
        showHoveredNodeLabel={true}
        nodeLabelAccessor={(node: any) => node.label}
      />
    </div>
  )
}

export default function DynamicGraphGenerationPage() {
  const [config, setConfig] = useState<{
    csvFile?: File
  }>({})
  const [result, setResult] = useState<{
    result?: {
      summary: string
      graphData: {
        nodes: GraphNode[]
        edges: GraphLink[]
        cosmographData: {
          nodes: GraphNode[]
          links: GraphLink[]
        }
      }
    }
    error?: string
    details?: string
    steps?: string[]
    executionTime?: string
  } | null>(null)
  const [isExecuting, setIsExecuting] = useState(false)
  const [activeTab, setActiveTab] = useState("config")
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [isDragging, setIsDragging] = useState(false)

  const handleFileChange = (files: FileList | null) => {
    if (files && files.length > 0) {
      const file = files[0]
      setConfig({ csvFile: file })
    }
  }

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setIsDragging(true)
  }

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setIsDragging(false)
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setIsDragging(false)
    
    const files = e.dataTransfer.files
    handleFileChange(files)
  }

  const executeAlgorithm = async () => {
    setIsExecuting(true)
    setActiveTab("result")

    try {
      const file = config.csvFile
      if (!file) {
        throw new Error("请先上传CSV文件")
      }

      const startTime = Date.now()
      const fileContent = await new Promise<string>((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = (e) => resolve(e.target?.result as string)
        reader.onerror = reject
        reader.readAsText(file)
      })

      const rows = fileContent.split("\n").map(row => row.split(";"))
      const headers = rows[0]
      
      const nodes = new Map<string, GraphNode>()
      const edges: GraphLink[] = []

      rows.slice(1).forEach(row => {
        if (row.length < 5) return

        const [source, target, value, color, date] = row.map(cell => cell.trim().replace(/^"|"$/g, ''))
        const timestamp = new Date(date).getTime()

        if (!nodes.has(source)) {
          nodes.set(source, {
            id: source,
            label: `节点 ${source}`,
            color: color || "#4285F4",
            size: Math.log(parseInt(value) || 1) + 5,
            timestamp
          })
        }

        if (!nodes.has(target)) {
          nodes.set(target, {
            id: target,
            label: `节点 ${target}`,
            color: color || "#4285F4",
            size: Math.log(parseInt(value) || 1) + 5,
            timestamp
          })
        }

        edges.push({
          id: `edge-${edges.length}`,
          source,
          target,
          weight: parseInt(value) || 1,
          timestamp
        })
      })

      const nodesArray = Array.from(nodes.values())
      const cosmographData = {
        nodes: nodesArray,
        links: edges
      }

      const timestamps = [...nodesArray.map(n => n.timestamp)]
      const startDate = new Date(Math.min(...timestamps))
      const endDate = new Date(Math.max(...timestamps))
      const executionTime = Date.now() - startTime

      setResult({
        result: {
          summary: `解析完成！
节点数量: ${cosmographData.nodes.length}
边数量: ${cosmographData.links.length}
时间范围: ${startDate.toLocaleDateString()} 至 ${endDate.toLocaleDateString()}`,
          graphData: {
            nodes: cosmographData.nodes,
            edges: cosmographData.links,
            cosmographData
          }
        },
        steps: [
          "解析CSV数据文件...",
          "提取节点和边信息...",
          "构建图结构...",
          "计算图属性...",
          "准备可视化数据..."
        ],
        executionTime: `${executionTime}ms`
      })
    } catch (error) {
      console.error("算法执行错误:", error)
      setResult({
        error: "算法执行过程中发生错误",
        details: error instanceof Error ? error.message : String(error)
      })
    } finally {
      setIsExecuting(false)
    }
  }

  return (
    <div>
      <div className="flex flex-col gap-4">
        <div>
          <h1 className="text-3xl font-bold">动态异构图展示</h1>
          <p className="text-muted-foreground mt-2">支持10万级别多层动态异构网络的展示</p>
        </div>

        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="config">配置</TabsTrigger>
            <TabsTrigger value="result">结果</TabsTrigger>
          </TabsList>

          <TabsContent value="config">
            <Card>
              <CardHeader>
                <CardTitle>算法配置</CardTitle>
                <CardDescription>设置算法参数并执行</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="csvFile">上传CSV数据文件</Label>
                  <div
                    className={`flex flex-col items-center justify-center border-2 border-dashed rounded-md p-6 cursor-pointer transition-colors ${
                      isDragging ? "border-primary bg-primary/10" : "hover:bg-muted/50"
                    }`}
                    onClick={() => fileInputRef.current?.click()}
                    onDragOver={handleDragOver}
                    onDragLeave={handleDragLeave}
                    onDrop={handleDrop}
                  >
                    <input
                      ref={fileInputRef}
                      type="file"
                      id="csvFile"
                      accept=".csv"
                      className="hidden"
                      onChange={(e) => handleFileChange(e.target.files)}
                    />
                    <Upload className="h-10 w-10 text-muted-foreground mb-2" />
                    <p className="text-sm text-muted-foreground">
                      {config.csvFile ? config.csvFile.name : "点击或拖拽文件到此处上传"}
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">支持 .csv 格式</p>
                  </div>
                </div>
              </CardContent>
              <CardFooter>
                <Button onClick={executeAlgorithm} disabled={isExecuting} className="w-full">
                  {isExecuting ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      执行中...
                    </>
                  ) : (
                    <>
                      <Play className="mr-2 h-4 w-4" />
                      执行算法
                    </>
                  )}
                </Button>
              </CardFooter>
            </Card>
          </TabsContent>

          <TabsContent value="result">
            <Card>
              <CardHeader>
                <CardTitle>执行结果</CardTitle>
                <CardDescription>
                  {isExecuting
                    ? "算法正在执行中..."
                    : result
                      ? `执行完成，耗时: ${result.executionTime}`
                      : "尚未执行算法"}
                </CardDescription>
              </CardHeader>
              <CardContent>
                {isExecuting ? (
                  <div className="flex flex-col items-center justify-center py-8">
                    <Loader2 className="h-8 w-8 animate-spin text-primary mb-4" />
                    <p>正在执行算法，请稍候...</p>
                  </div>
                ) : result ? (
                  <div className="space-y-4">
                    {result.error ? (
                      <Alert variant="destructive">
                        <AlertTitle>{result.error}</AlertTitle>
                        <AlertDescription>{result.details}</AlertDescription>
                      </Alert>
                    ) : (
                      <>
                        <div>
                          <h3 className="text-lg font-medium mb-2">数据摘要</h3>
                          <div className="p-4 bg-muted rounded-md">
                            <pre className="whitespace-pre-wrap">{result.result?.summary}</pre>
                          </div>
                        </div>

                        <Separator />

                        <div>
                          <h3 className="text-lg font-medium mb-2">执行步骤</h3>
                          <div className="space-y-2">
                            {result.steps?.map((step: string, index: number) => (
                              <div key={index} className="p-2 border rounded-md">
                                <p>{step}</p>
                              </div>
                            ))}
                          </div>
                        </div>

                        <Separator />

                        <div>
                          <h3 className="text-lg font-medium mb-2">图谱可视化</h3>
                          <div className="h-[800px] w-full border rounded-lg overflow-hidden bg-black">
                            {result?.result?.graphData && (
                              <GraphComponent 
                                nodes={result.result.graphData.cosmographData.nodes}
                                links={result.result.graphData.cosmographData.links}
                              />
                            )}
                          </div>
                        </div>
                      </>
                    )}
                  </div>
                ) : (
                  <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
                    <p>请先配置并执行算法</p>
                  </div>
                )}
              </CardContent>
              <CardFooter>
                <Button onClick={executeAlgorithm} disabled={isExecuting} className="w-full">
                  {isExecuting ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      执行中...
                    </>
                  ) : (
                    <>
                      <Play className="mr-2 h-4 w-4" />
                      重新执行
                    </>
                  )}
                </Button>
              </CardFooter>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  )
} 